/*****************************************************************************
 * $LastChangedDate: 2011-04-23 21:07:07 -0400 (Sat, 23 Apr 2011) $
 * @file
 * @author  Jim E. Brooks  http://www.palomino3d.org
 * @brief   ImageCache class.
 *//*
 * LEGAL:   COPYRIGHT (C) 2008 JIM E. BROOKS
 *          THIS SOURCE CODE IS RELEASED UNDER THE TERMS
 *          OF THE GNU GENERAL PUBLIC LICENSE VERSION 2 (GPL 2).
 *****************************************************************************/

#define FX_IMAGE_CACHE_CC 1
#include <utility>
#include "base/module.hh"
#include "base/conf.hh"
using namespace base;
#include "fx/module.hh"
#include "fx/image_cache.hh"

#include <osgDB/Registry>
#include <osgDB/ReadFile>

namespace fx {

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////  ImageCache  //////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

ImageCache* ImageCache::msInstance;

/*****************************************************************************
 * ctor/dtor.
 *****************************************************************************/
ImageCache::ImageCache( void )
:   mImageMap()
{
    // NOP
}

ImageCache::~ImageCache()
{
    // NOP
}

/*****************************************************************************
 * Load image from either file or cache (STL map).
 * MIGHT THROW C++ EXCEPTION.
 *****************************************************************************/
RefPtr<osg::Image>
ImageCache::LoadImage( const string& filename )
{
    // Was image loaded before?
    ImageMap::iterator iter = mImageMap.find( filename );
    if ( iter == mImageMap.end() )
    {
        // Not cached.  Load from file.
        const string pathname = string(base::GetDataDir()) + string("/") + string(filename);
        RefPtr0<osg::Image> image = osgDB::readImageFile( pathname );

        // Load error?
        if ( UX( image == NULL ) )
        {
            throw Exception( string("ERROR: cannot load image file ") + pathname );
        }

        // Store in cache (by filename, not full pathname).
        mImageMap.insert( std::make_pair( filename, image ) );

        return image.get();
    }
    else
    {
        // Inside cache.
        return iter->second;  // RefPtr<osg::Image>
    }
}

} // namespace fx
